﻿using InfonavaEye.common;
using InfonavaEye.model;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using Color = System.Drawing.Color;
using Pen = System.Drawing.Pen;

namespace InfonavaEye
{
    public partial class MainForm
    {
        BoxModel boxModel = null;
        Color mainColor = Color.FromArgb(255, 180, 180, 180);
        int margin = 600;
        int paddingTop = 900;
        int paddingBottom = 300;
        int paddingH = 500;
        int nailWidth = 400;
        int nailHeight = 400;
        float scaleRate = 1 / 32f;
        //Dictionary<string, Nail> nailMap = new Dictionary<string, Nail>();
        public List<Nail> nailList = new List<Nail>();
        int fixX = 0;
        int fixY = 0;
        Graphics drawG = null;

        private void drawAreas()
        {
            if (drawG ==null) {
                drawG = pictureBox.CreateGraphics();
                GraphicsHelper.SetGDIHigh(drawG);
            }

            Color areaColor = Color.Red ;// Color.FromArgb(255, 250, 250, 250);
            Color bgColor = Color.FromArgb(255, 233, 233, 233);
            GraphicsHelper.FillRoundRectangle(pictureBox.ClientRectangle, drawG, 15, bgColor);

            if (this.boxModel == null || this.boxModel.boxAreas == null || this.boxModel.boxAreas.Count == 0) return;

            nailList.Clear();
            int minX = (this.boxModel.boxAreas.Min(p => p.startPoint[0]));
            int minY = (this.boxModel.boxAreas.Min(p => p.startPoint[1]));
            /* int maxX = (this.boxModel.boxAreas.Max(p => p.startPoint[0]));
                int maxY = (this.boxModel.boxAreas.Max(p => p.startPoint[1]));*/
            /* int maxWidth = maxX - minX;
                int maxHeight = maxY - minY;*/
            fixX = 0 - minX;
            fixY = 0 - minY;

            var nailMap = AutoStartParams.nailListToMap(this.templateNailList);
            this.boxModel.boxAreas.ForEach((area) =>
            {
                try
                {
                    //Console.WriteLine("绘制区域:" + area.name);
                    var startPoint = area.startPoint;

                    //画外框
                    var x = startPoint[0] + fixX + margin;
                    var y = startPoint[1] + fixY + margin;
                    var width = area.holdPitch[0] * (area.columnCount - 1) + 2 * (paddingH);
                    var height = area.holdPitch[1] * (area.rowCount - 1) + (paddingTop + paddingBottom);
                    var newPoint = flipXY((int)(x * scaleRate), (int)(y * scaleRate));
                    //Console.WriteLine("绘制区域参数：x {0}，y {1},width {2},height {3}", x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
                    var areaPath = GraphicsHelper.DrawRoundRect((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate), 15);
                    drawG.DrawPath(new Pen(mainColor, 1), areaPath);

                    //画螺钉
                    for (int i = 0; i < area.columnCount; i++)
                    {
                        for (int j = 0; j < area.rowCount; j++)
                        {
                            var nailKey = string.Format(AutoStartParams.NAIL_MAP_KEY_FORMAT, area.code, i, j);
                            if (nailMap == null || !nailMap.ContainsKey(nailKey))
                            {
                                Console.WriteLine("nailMap中不存在key:" + nailKey);
                                return;
                            }
                            var img = nailMap[nailKey].status == NailStatus.Selected ? Properties.Resources.nail_plus : Properties.Resources.nail_empty;
                            this.drawNail(i, j, area, img);
                        }
                    }
                    //g.Dispose();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("绘制区域发生异常：{0}，{1}", ex.Message, ex.StackTrace);
                }
            });
        }

        /// <summary>
        /// 翻转X轴坐标
        /// （使图像本来显示在左侧的，现在显示到右侧）
        /// </summary>
        private System.Windows.Point flipXY(int x, int y)
        {
            int centerX = pictureBox.Width / 2;
            int centerY = pictureBox.Height / 2;
            var transform = new RotateTransform() { Angle = 180, CenterX = centerX, CenterY = centerY };
            return transform.Transform(new System.Windows.Point(x, y));
        }

        private void drawNail(int i, int j, BoxArea area, Bitmap img)
        {
            var startPoint = area.startPoint;
            var columnTitles = area.columnTitle;
            var width = nailWidth;
            var height = nailHeight;
            /*if (i == 0 && j == 0)
            {
                width = (int)Math.Round(nailWidth * 1.5, 0);
                height = (int)Math.Round(nailWidth * 1.5, 0);
            }*/
            var x = startPoint[0] + fixX + area.holdPitch[0] * i + paddingH + margin - (width) / 2;
            var y = startPoint[1] + fixY + area.holdPitch[1] * j + paddingTop + margin - (height) / 2;
            var newPoint = flipXY((int)(x * scaleRate), (int)(y * scaleRate));
            Rectangle r = new Rectangle((int)newPoint.X - (int)(width * scaleRate), (int)newPoint.Y - (int)(height * scaleRate), (int)(width * scaleRate), (int)(height * scaleRate));

            nailList.Add(new Nail()
            {
                status = NailStatus.Normal,
                area = area,
                point = new Point(i, j),
                location = r,
            });
            //Console.WriteLine("绘制钉子 ({0})：x {1}，y {2},width {3},height {4}", i + ":" + j, x * scaleRate, y * scaleRate, width * scaleRate, height * scaleRate);
            drawG.DrawImage(img, r);
            //第一排头部写上数字
            if (j == 0 && (columnTitles.Count() - 1) >= i)
            {
                drawText(drawG, r, columnTitles[i]);
            }
        }
        private void drawText(Graphics graphics, Rectangle nailRect, string text)
        {
            var enlargeWidth = 20;
            var enlargeHeight = 5;
            Rectangle textRect = new Rectangle(nailRect.X - enlargeWidth / 2, nailRect.Y +20 - enlargeHeight / 2, nailRect.Width + enlargeWidth, nailRect.Height + enlargeHeight);
            Font LabelFont = new Font("黑体", 9, FontStyle.Regular); //设置字体、字号、是否加粗
            SolidBrush labelColor = new SolidBrush(Color.FromArgb(255, 99, 99, 99));//设置字体颜色
            StringFormat sf = new StringFormat();//位置对象
            sf.Alignment = StringAlignment.Center;//居中
            graphics.DrawString(text, LabelFont, labelColor, textRect, sf);
        }

        Graphics boxG = null;
        private void updateNailStatus(OCRResult result)
        {
            if (this.boxModel == null) return;
            try
            {
                var nail = result.nail;
                if (nail != null)
                {
                    var point = nail.point;

                    GraphicsHelper.SetGDIHigh(drawG);
                    GraphicsHelper.FillRoundRectangle(nail.location, drawG, 15, pictureBox.BackColor);
                    Console.WriteLine("更新钉子 ({0})：x {1}，y {2},width {3},height {4},status:{5}", point.X + ":" + point.Y, nail.location.X, nail.location.Y, nail.location.Width, nail.location.Height, nail.status);
                    var img = FormDataBridge.DEFAULT_CODE.Equals(result.code) ? Properties.Resources.nail_plus_yellow : (
                        checkResult(result.code) ? Properties.Resources.nail_plus_green : Properties.Resources.nail_plus_green);
                    Console.WriteLine("nail.status:" + nail.status);
                    this.drawNail(point.X, point.Y, nail.area, img);
                }
                else {
                    Console.WriteLine("更新钉子,nail数据为空 rowNum:{0}", result.rowNum);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {

            }
        }

        private bool checkResult(string code)
        {
            return !string.IsNullOrEmpty(code)  && !code.Equals("ERROR") && !code.Equals("仅采样");
        }
    }
}
